<template>
  <div class="tournament-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>赛事管理</span>
        </div>
      </template>
      <div class="content-body">
        <!-- 搜索和筛选区域 -->
        <div class="search-filter">
          <el-input 
            v-model="queryForm.name" 
            placeholder="请输入赛事标题搜索"
            style="width: 200px; margin-right: 10px;"
            prefix-icon="Search"
            clearable
          />
          <el-select 
            v-model="queryForm.category" 
            placeholder="请选择赛事分类"
            style="width: 150px; margin-right: 10px;"
            clearable
          >
            <el-option label="大满贯" value="大满贯" />
            <el-option label="ATP巡回赛" value="ATP巡回赛" />
            <el-option label="WTA巡回赛" value="WTA巡回赛" />
            <el-option label="挑战赛" value="挑战赛" />
            <el-option label="卫星赛" value="卫星赛" />
            <el-option label="硬地赛" value="硬地赛" />
            <el-option label="红土赛" value="红土赛" />
            <el-option label="草地赛" value="草地赛" />
            <el-option label="室内赛" value="室内赛" />
          </el-select>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="handleAddTournament">新增赛事</el-button>
        </div>
        
        <!-- 赛事列表 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="id" label="赛事ID" width="80" />
          <el-table-column prop="category" label="赛事分类" width="120" />
          <el-table-column prop="name" label="赛事标题" width="200" :show-overflow-tooltip="true" />
          <el-table-column prop="createTime" label="发布时间" width="180" />
          <el-table-column label="封面图" width="120">
            <template #default="scope">
              <el-image 
                v-if="scope.row.picUrl"
                :src="scope.row.picUrl"
                :preview-src-list="[scope.row.picUrl]"
                style="width: 80px; height: 50px; border-radius: 4px;"
              />
              <span v-else>暂无</span>
            </template>
          </el-table-column>
          <el-table-column label="视频" width="120">
            <template #default="scope">
              <el-button 
                v-if="scope.row.videoUrl" 
                type="primary" 
                size="small" 
                @click="playVideo(scope.row.videoUrl)"
                :icon="VideoPlay"
              >
                播放
              </el-button>
              <span v-else>暂无</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDeleteTournament(scope.row.id)"
                v-if="!isDeleting"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px; text-align: right;">
          <el-pagination 
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑赛事弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="700px"
      @close="resetForm"
    >
      <el-form 
        ref="tournamentFormRef" 
        :model="tournamentForm" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="赛事标题" prop="title">
          <el-input v-model="tournamentForm.title" placeholder="请输入赛事标题" />
        </el-form-item>
        <el-form-item label="赛事分类" prop="category">
          <el-select v-model="tournamentForm.category" placeholder="请选择赛事分类">
            <el-option label="大满贯" value="大满贯" />
            <el-option label="ATP巡回赛" value="ATP巡回赛" />
            <el-option label="WTA巡回赛" value="WTA巡回赛" />
            <el-option label="挑战赛" value="挑战赛" />
            <el-option label="卫星赛" value="卫星赛" />
            <el-option label="硬地赛" value="硬地赛" />
            <el-option label="红土赛" value="红土赛" />
            <el-option label="草地赛" value="草地赛" />
            <el-option label="室内赛" value="室内赛" />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            class="image-upload"
            drag
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleImageUploadSuccess"
            :on-error="handleImageUploadError"
            :before-upload="beforeImageUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <div v-if="!tournamentForm.coverImage">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽图片到此处或 <em>点击上传</em>
              </div>
            </div>
            <div v-else class="image-preview">
              <img 
                :src="tournamentForm.coverImage" 
                alt="赛事封面图" 
                class="uploaded-image"
              >
              <el-button 
                type="danger" 
                size="small" 
                @click.stop="removeImage"
              >
                删除图片
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频" prop="videoUrl">
          <el-upload
            class="video-upload"
            drag
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleVideoUploadSuccess"
            :on-error="handleVideoUploadError"
            :before-upload="beforeVideoUpload"
            :show-file-list="false"
            accept="video/*"
          >
            <div v-if="!tournamentForm.videoUrl">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽视频到此处或 <em>点击上传</em>
              </div>
            </div>
            <div v-else class="video-preview">
              <video :src="tournamentForm.videoUrl" controls class="uploaded-video" />
              <el-button 
                type="danger" 
                size="small" 
                @click.stop="removeVideo"
              >
                删除视频
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 视频播放弹窗 -->
    <el-dialog 
      v-model="videoVisible" 
      title="视频播放"
      width="800px"
      @close="closeVideo"
    >
      <div style="display: flex; justify-content: center;">
        <video 
          v-if="currentVideoUrl" 
          :src="currentVideoUrl" 
          controls 
          style="max-width: 100%; max-height: 500px;"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, ElImage } from 'element-plus'
import { Search, Upload, VideoPlay, UploadFilled } from '@element-plus/icons-vue'
import { tournamentList, tournamentAdd, tournamentDelete } from '@/request/tournament.js'

const queryForm = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  category: '' // 新增分类搜索字段
})

// 上传配置
const uploadUrl = '/api/system/file/uploadFile'
const uploadHeaders = {
  Authorization: localStorage.getItem('token') || ''
}

const isDeleting = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增赛事')
const tournamentFormRef = ref(null)
const editingTournamentId = ref(null)

// 视频播放相关
const videoVisible = ref(false)
const currentVideoUrl = ref('')

const tableData = ref([])
const total = ref(0)

const getList=()=>{
  tournamentList(queryForm.value).then(res=>{
    tableData.value = res.records
    total.value = res.total
    tableData.value.forEach(item => {
      item.picUrl = "/api"+item.picUrl
      item.videoUrl = "/api"+item.videoUrl
    })
  })
}
getList()

// 赛事表单
const tournamentForm = reactive({
  title: '',
  category: '', // 新增赛事分类字段
  coverImage: '',
  videoUrl: ''
})


// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入赛事标题', trigger: 'blur' },
    { min: 2, max: 100, message: '赛事标题长度应在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请上传封面图', trigger: 'change' }
  ],
  videoUrl: [
    { required: true, message: '请上传视频', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择赛事分类', trigger: 'change' }
  ]

}

// 重置表单
  const resetForm = () => {
    if (tournamentFormRef.value) {
      tournamentFormRef.value.resetFields()
    }
    editingTournamentId.value = null
    Object.keys(tournamentForm).forEach(key => {
      tournamentForm[key] = ''
    })
  }



// 新增赛事
const handleAddTournament = () => {
  dialogTitle.value = '新增赛事'
  resetForm()
  dialogVisible.value = true
}


// 提交表单
  const handleSubmit = async () => {
    tournamentFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          // 创建提交表单数据的副本，避免直接修改原表单
          const submitData = { ...tournamentForm } 
          // 处理封面图URL格式 - 只有API返回的URL需要去掉/api前缀
          if (submitData.coverImage && submitData.coverImage.startsWith('/api')) {
            submitData.coverImage = submitData.coverImage.substring(4)
  }
  
  // 处理视频URL格式 - 只有API返回的URL需要去掉/api前缀
  if (submitData.videoUrl && submitData.videoUrl.startsWith('/api')) {
    submitData.videoUrl = submitData.videoUrl.substring(4)
  }
          
          // 提交时检查
          if (!submitData.coverImage) {
            ElMessage.error('请上传封面图！')
            return
          }
          if (editingTournamentId.value) {
            // 编辑模式
            
          } else {
            let submitForm = {
              name: submitData.title,
              category: submitData.category,
              videoUrl: submitData.videoUrl,
              picUrl: submitData.coverImage
            }
            // 新增模式
            tournamentAdd(submitForm).then(res => {
              ElMessage.success('赛事添加成功')
              dialogVisible.value = false
              resetForm()
              getList()
            })
          }
        } catch (error) {
          ElMessage.error('操作失败，请重试')
        }
      }
    })
  }

// 图片上传成功
const handleImageUploadSuccess = (response, file) => {
  console.log('图片上传响应:', response)
  if (response && response.data) {
    tournamentForm.coverImage = '/api' + response.data
  } else {
    // 创建本地URL用于预览，但实际提交时可能需要调整
    tournamentForm.coverImage = URL.createObjectURL(file.raw)
  }
  console.log('当前tournamentForm:', tournamentForm)
  ElMessage.success('图片上传成功')
}

// 图片上传失败
const handleImageUploadError = (error) => {
  ElMessage.error('图片上传失败')
}

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB！')
    return false
  }
  return true
}

// 删除图片
const removeImage = () => {
  tournamentForm.coverImage = ''
}

// 视频上传成功
const handleVideoUploadSuccess = (response, file) => {
  console.log('视频上传响应:', response)
  if (response && response.data) {
    tournamentForm.videoUrl = '/api' + response.data
  } else {
    // 创建本地URL用于预览，但实际提交时可能需要调整
    tournamentForm.videoUrl = URL.createObjectURL(file.raw)
  }
  console.log('当前tournamentForm:', tournamentForm)
  ElMessage.success('视频上传成功')
}

// 视频上传失败
const handleVideoUploadError = (error) => {
  ElMessage.error('视频上传失败')
}

// 上传前检查
const beforeVideoUpload = (file) => {
  const isVideo = file.type.startsWith('video/')
  const isLt200M = file.size / 1024 / 1024 < 200
  
  if (!isVideo) {
    ElMessage.error('只能上传视频文件！')
    return false
  }
  if (!isLt200M) {
    ElMessage.error('视频大小不能超过 200MB！')
    return false
  }
  return true
}

// 删除视频
const removeVideo = () => {
  tournamentForm.videoUrl = ''
}

// 播放视频
const playVideo = (videoUrl) => {
  currentVideoUrl.value = videoUrl
  videoVisible.value = true
}

// 关闭视频播放
const closeVideo = () => {
  currentVideoUrl.value = ''
  videoVisible.value = false
}

// 删除赛事
const handleDeleteTournament = (id) => {
  ElMessageBox.confirm('确定要删除这个赛事吗？删除后无法恢复。', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isDeleting.value = true
    // 模拟API调用
    setTimeout(() => {
      const index = mockTournaments.findIndex(item => item.id === id)
      if (index !== -1) {
        mockTournaments.splice(index, 1)
      }
      ElMessage.success('赛事删除成功')
      isDeleting.value = false
      getList()
    }, 500)
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 分页相关方法
const handleSizeChange = (size) => {
  queryForm.value.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  queryForm.value.pageNum = current
  getList()
}
</script>

<style scoped>

.content-body {
  padding-top: 10px;
}

.search-filter {
  display: flex;
  align-items: center;
}

.image-preview,
.video-preview {
  margin-top: 10px;
}

.image-preview,
.video-preview {
  margin-top: 10px;
}

.image-preview h4,
.video-preview h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #606266;
}

/* 限制上传图片的大小 */
.uploaded-image {
  max-width: 300px;
  max-height: 200px;
  border: 1px solid #ddd;
  padding: 5px;
  border-radius: 4px;
}

/* 限制上传视频的大小 */
.uploaded-video {
  max-width: 500px;
  max-height: 300px;
  border: 1px solid #ddd;
  padding: 5px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>